import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginView.vue'),
    meta: {
      requiresAuth: false // 不需要登录即可访问
    }
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/RegisterView.vue'),
    meta: {
      requiresAuth: false // 不需要登录即可访问
    }
  },
  {
    path: '/mapview1',
    name: 'mapview1',
    component: () => import('../views/MapView1.vue'),
    meta: {
      requiresAuth: true // 需要登录才能访问
    }
  },
  {
    path: '/mapview2',
    name: 'mapview2',
    component: () => import('../views/MapView2.vue'),
    meta: {
      requiresAuth: true // 需要登录才能访问
    }
  },
  {
    path: '/mapview3',
    name: 'mapview3',
    component: () => import('../views/MapView3.vue'),
    meta: {
      requiresAuth: true // 需要登录才能访问
    }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {
  document.body.removeAttribute('style')
  next()
  // 判断路由是否需要登录才能访问
  if (to.meta.requiresAuth && !localStorage.getItem('token')) {
    // 如果用户没有登录并且要跳转的页面需要登录，则跳转到登录页面
    next({ path: '/login' })
  } else if (to.name === 'login' && localStorage.getItem('token')) {
    // 如果用户已经登录并且要跳转到登录页面，则直接跳转到首页
    next({  })
  } else {
    next() // 否则允许跳转
  }
})

export default router